package com.wq.gof.designer.chain.list;

import com.wq.gof.designer.chain.EventHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wangqiang20995
 * @Date:2019/1/25
 * @Description:
 * @Resource:
 */
public class HandlerContext {

    private List<EventHandler> handlers;

    private volatile int currentHandler;

    private Object monitor =  new Object();

    public HandlerContext(){
        handlers = new ArrayList<>(100);
        currentHandler = 0;
    }

    public void addLastHandler(EventHandler eventHandler){
        synchronized (monitor) {
            handlers.add(eventHandler);
        }
    }

    public void addHandler(int index,EventHandler eventHandler){
        synchronized (monitor) {
            handlers.add(index, eventHandler);
        }
    }

    public void addFirstHandler(EventHandler eventHandler){
        synchronized (monitor) {
            List<EventHandler> list = new ArrayList<>(handlers.size() + 1);
            list.add(eventHandler);
            list.addAll(handlers);

            this.handlers = list;
        }
    }

    public void doHandler(Object conditions){
        if(this.currentHandler >= handlers.size()){
            throw new IllegalStateException("并发错误，指针下标异常");
        }

        EventHandler handler;
        synchronized (monitor){
            handler = this.handlers.get(this.currentHandler);
            this.currentHandler ++;
        }

        handler.handle(conditions);
    }

    //这个方法必须的，因为每一次handler匹配到之后调用完成，如果后序还有新的handler请求进来要执行，那么就是从头开始匹配执行，所以相当于重置
    public void resume(){
        synchronized (monitor) {
            this.currentHandler = 0;
        }
    }
}
